<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>增加一列表格</title>
		<script type="text/javascript" src="../js/jquery-1.8.3.js"></script>
		<script type="text/javascript" src="../js/easyui/jquery.easyui.min.js"></script>
		<script type="text/javascript" src="../js/easyui/locale/easyui-lang-zh_CN.js"></script>
		<link rel="stylesheet" href="../js/easyui/themes/default/easyui.css" />
		<link rel="stylesheet" href="../js/easyui/themes/icon.css" />
		<script type="text/javascript">
			$(function() {
				$("#grid").datagrid({
					columns: [
						[{
							field: 'id',
							title: '编号',
							width: 100,
							editor: {
								type: 'validatebox',
								options: {
									required: true
								}
							}
						}, {
							field: 'name',
							title: '名字',
							width: 100,
							editor: {
								type: 'validatebox',
								options: {
									required: true
								}
							}
						}, {
							field: 'price',
							title: '价格',
							width: 100,
							editor: {
								type: 'validatebox',
								options: {
									required: true
								}
							}
						}]
					],
					toolbar: [{
						id: 'add',
						text: '添加',
						iconCls: 'icon-add',
						handler: function() {
							//表示正在编辑
							if(currentIndex != undefined) {
								return;
							}
							// 插入一行新的数据，到首行 
							$("#grid").datagrid('insertRow', {
								index: 0,
								row: {} // 创建一个空对象 
							});
							// 开启编辑状态 
							$("#grid").datagrid('beginEdit', 0);

							//保存全局变量
							currentIndex = 0;
						}
					}, {
						id: 'edit',
						text: '编辑',
						iconCls: 'icon-edit',
						handler: function() {
							var row = $("#grid").datagrid('getSelected');
							var index = $("#grid").datagrid('getRowIndex', row);
							$("#grid").datagrid('beginEdit', index);
							
							//保存到全局变量
							currentIndex = index;
						}
					}, {
						id: 'save',
						text: '保存',
						iconCls: 'icon-save',
						handler: function() {
							// 保存编辑效果 
							$("#grid").datagrid('endEdit', currentIndex);
						}
					}, {
						id: 'cancel',
						text: '取消',
						iconCls: 'icon-cancel',
						handler: function() {
							// 保存编辑效果 
							$("#grid").datagrid('cancelEdit', currentIndex);
//							currentIndex = undefined;
						}
					}],
					url:'product.json',
					singleSelect:true,
					onAfterEdit:function(rowIndex, rowData, changes){
						//保存成功后,才会触发该事件
						currentIndex = undefined;//保存成功后 将选中的置为空
					}
				});
				//定义一个全局变量
				var currentIndex;
			});
		</script>
	</head>

	<body>
		<table id="grid"></table>
	</body>

</html>